/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package networkowner;

import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import contractmessageservice.ContractMessage;
import electricitysupplier.ReceiveAperak;
import electricitysupplier.ResponseMessage;
import electricitysupplier.T1ES1;
import electricitysupplier2.TestService;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.stream.StreamSource;

/**
 *
 * @author ool
 */
@MessageDriven(mappedName = "jms/esit1no1_Queue", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class Esit1no1mdb implements MessageListener {
    
   private static final String T1NO1 = "T1NO1";
    private static final String T1ES1 = "T1ES1";
    private T1ES1 service;
    private TestService es2Service;
    private Esit1no1Dao dao;
    private MessageValidatorService messageValidatorService;

    public Esit1no1mdb() {
        messageValidatorService = new MessageValidatorService();
        dao = new Esit1no1Dao();
        service = new T1ES1();
        es2Service = new TestService();
    }

    @Override
    public void onMessage(Message message) {
        try {
            TextMessage msg = (TextMessage) message;
            JAXBContext context = JAXBContext.newInstance(ContractMessage.class);
            Unmarshaller um = context.createUnmarshaller();
            ContractMessage contractMessage = (ContractMessage) um.unmarshal(new StreamSource(new StringReader((msg.getText()))));
            int id = dao.insertRecievedMessage(msg.getText());

            ResponseMessage resp = createResponse(contractMessage, id);
            messageValidatorService.validateContractMessage(contractMessage, resp);

            if (T1ES1.equals(contractMessage.getProviderParty().getName())) {
                sendAperakToES1(resp);
            } else {
                sendAperakToES2(contractMessage.getClientParty().getRegistryCode(), resp.isAccepted());
            }
            Logger.getLogger(Esit1no1mdb.class.getName()).log(Level.INFO, "SUCCESS");
        } catch (JMSException ex) {
            Logger.getLogger(Esit1no1mdb.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(Esit1no1mdb.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private ResponseMessage createResponse(ContractMessage contractMessage, int id) {
        ResponseMessage resp = new ResponseMessage();

        resp.setMessageRecieverParty(contractMessage.getMessageSenderParty());
        resp.setMessageSenderParty(T1NO1);
        resp.setMessageId(Integer.toString(id));

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(new Date());
        XMLGregorianCalendar xmlCal = new XMLGregorianCalendarImpl(cal);
        resp.setTime(xmlCal);

        resp.setProcessedMessageId(contractMessage.getMessageId());
        return resp;
    }

    private void sendAperakToES1(ResponseMessage msg) throws JAXBException {
        String text = responseMessageToString(msg);
        
        int id = dao.insertComposedMessage(text);
        msg.setMessageId(Integer.toString(id));

        electricitysupplier.IT1ES1Service port = service.getBasicHttpBindingIT1ES1Service();
        port.receiveAperak(msg);
    }

    private String responseMessageToString(ResponseMessage msg) throws JAXBException {
        ReceiveAperak aperak = new ReceiveAperak();
        aperak.setMsg(msg);
        JAXBContext context = JAXBContext.newInstance(ReceiveAperak.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(aperak, writer);
        return writer.toString();
    }

    private void sendAperakToES2(String clientRegCode, boolean isApproved) {
        if (isApproved) {
            dao.insertComposedMessage("<clientApproved><registrationCode>" + clientRegCode + "</registrationCode></clientApproved>");
            es2Service.getTestServiceSoap().clientApproved(clientRegCode);
        } else {
            dao.insertComposedMessage("<clientLeaving><registrationCode>" + clientRegCode + "</registrationCode></clientLeaving>");
            es2Service.getTestServiceSoap().clientLeaving(clientRegCode);
        }
    }
}
